var btn = document.querySelector('button[type="button"]');
var username = document.querySelector('[name="username"]');
//判断cookie中是否有remusername
var remusername = getCookie('username');
if(remusername){
        username.value = remusername;
}

var password = document.querySelector('[name="password"]');
var remember = document.querySelector('[name="remember"]');

btn.onclick = function(){
    if(username.value === ''){
        alert("用户名不能为空")
        return false
    }
    if(password === ''){
        alert("密码不能为空")
        return false;
    }
    // 发送ajax
    var xhr = new XMLHttpRequest;
    xhr.open("post",'./php/login.php');
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4){
            if(parseInt(xhr.status/100)===2){
                var res = xhr.responseText;
                // console.log(res);
                if(res == 1){
                    //设置cookie
                    setCookie('username',username.value,7200);
                    //判断是否选中了记住
                    if(remember.checked){
                        setCookie('remusername',remusername.value,24*3600*7);
                    }
                    alert("登陆成功");
                    
                    // 检测本地存储中是否存过url - 跳转到url，没有就跳转首页
                    var url = localStorage.getItem('url');
                    if(url){
                        //跳转之前先清除掉之前的url
                        localStorage.removeItem('url');
                        location.href = url;
                        return false;
                    }
                    location.href = "index.html";
                }else{
                    alert("用户名或密码错误");
                    return false;
                }
            }
        }
    }
    xhr.setRequestHeader("content-type",'application/x-www-form-urlencoded');
    xhr.send(`username=${username.value}&password=${password.value}`);
}
